package com.boot.springboot.service;



import com.boot.springboot.pojo.Staff;
import com.boot.springboot.pojo.dto.StaffDto;
import com.boot.springboot.repository.StaffRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service  //spring的bean
public class StaffService implements IStaffService {

    @Autowired
    StaffRepository staffRepository;

    @Override
    public Staff add(StaffDto staff) {
        Staff staffPojo = new Staff(); //创一个新的
        BeanUtils.copyProperties(staff, staffPojo); //把A拷到b里去，类似于复制
        // 修正：通过注入的实例调用save方法
        if (staffRepository.findByStaffId(staffPojo.getStaffId()).isPresent()) {
            throw new IllegalArgumentException("仓工ID已存在：" + staffPojo.getStaffId());
        }
        return staffRepository.save(staffPojo);
    }

    @Override
    public Staff get(Integer staffId) {
        return staffRepository.findByStaffId(staffId).orElseThrow(() -> {
            throw new IllegalArgumentException("不存在该仓工，异常参数");
        });
    }

    @Override
    public Staff edit(StaffDto staff) {
        Staff staffPojo = staffRepository.findByStaffId(staff.getStaffId())
                .orElseThrow(() -> new IllegalArgumentException("仓工不存在：" + staff.getStaffId()));
        BeanUtils.copyProperties(staff, staffPojo);
        return staffRepository.save(staffPojo);
    }

    @Transactional//JPA允许get方法通过非主键来进行查询，但detele不允许，所以为delete 方法开启一个数据库事务
    @Override
    public void delete(Integer staffId) {
        Staff staff=staffRepository.findByStaffId(staffId).orElseThrow(() -> new IllegalArgumentException("仓工不存在，staffId：" + staffId));
        staffRepository.deleteByStaffId(staffId);

    }
    @Override
    public List<Staff> getAllStaffs() {
        return (List<Staff>) staffRepository.findAll();
    }


}

